define([
  'jquery',
  'jqueryui',
  'underscore',
  'backbone',
  'backbonecollection',
  'models/lab/LabTestModel',
  'collections/lab/LabCollection',
  'text!templates/lab/testListTemplate.html',
  'msgbox',
  'multiselect'
], function($,JQueryUI, _, Backbone,BackboneCollection, LabTestModel,LabCollection, testListTemplate,MsgBox,Multiselect){

  var LabTestView = Backbone.View.extend({
    el: $(".mainpanel"),
    events: {'click #saveTests' : 'saveTests', 'change .testreading':'updatetestmodel'
        } ,
    initialize: function(){
    	var Collection = Backbone.PersistableCollection.extend({
    	    url: "/labTests"
    	});
    	this.labCollection = new Collection;
    },
    render: function(appointment){
 		   	

    	var self=this;
    	var labCollection = new LabCollection(null,{id:appointment.get("id")});
    	
    	var renderApp = _.after(1, function(){
            var data = {
          		  tests: labCollection.models,
          	        _: _ 
          	      };
    	      self.loadTemplate(data, labCollection);   
    	    //  self.latestTest=labCollection.models[0].get("examinations")[0].appointment.updatedOn;
    	      //self.labCollection.reset(labCollection.models[0].get("examinations")) ; 

        });
    	labCollection.fetch({ success: renderApp});

    },
    loadTemplate: function(data,labCollection){
 	    var compiledTemplate = _.template( testListTemplate, data );
  	    this.$el.html(compiledTemplate);
  },
    close: function(){
    	
    },
    saveTests: function(){
    	console.log(this.labCollection);
    	this.labCollection.save();
    	$.msgBox({
		    title:"Appment",
		    content:"Successfully Saved!",
		    type:"info"
		});

    },
    updatetestmodel: function(evt){
    	var changed=evt.currentTarget;
    	var value = $("#"+changed.id).val();
        var obj = "{\"test\": "+changed.id +",\"reading\":\""+value+"\"}";
        console.log(obj);
        var objInst = JSON.parse(obj);
        this.labCollection.add(objInst);
    	}

  });

  return LabTestView;
});
